package numbles.model;

import numbles.exceptions.FullColumnException;

public class Grid {

	private Numble[][] grid;
	private int width;
	private int height;
	
	public Grid(int width, int height) {
		this.grid = new Numble[width][height];
		this.width = width;
		this.height = height;
	}
	
	public Grid newInstance() {
		Grid grid = new Grid(this.width, this.height);
		for(int i = 0 ; i < width ; i++) {
			for(int j=0 ; j < height ; j++) {
				grid.setNumbleAt(i,j,getNumbleAt(i, j));
			}
		}
		return grid;
	}
	
	public final Numble getNumbleAt(int x, int y) {
		return grid[x][y];
	}
	
	public final Numble getNumbleAt(Coordinates coordinates) {
		return grid[coordinates.getX()][coordinates.getY()];
	}
	
	public Coordinates letNumbleFall(int x, final Numble numble) throws FullColumnException {
		for(int i = height - 1 ; i >= 0 ; i--) {
			if(grid[x][i] == null) {
				grid[x][i] = numble;
				return new Coordinates(x, i);
			}
		}
		throw new FullColumnException();
	}
	
	public void setNumbleAt(int x, int y, final Numble numble) {
		grid[x][y] = numble;
	}
	
	public void setNumbleAt(Coordinates coordinates, final Numble numble) {
		grid[coordinates.getX()][coordinates.getY()] = numble;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
	
	public void deleteNumbleAt(int x, int y) {
		grid[x][y] = null;
 	}
	
	public void deleteNumbleAt(Coordinates coordinates) {
		grid[coordinates.getX()][coordinates.getY()] = null;
	}
}
